﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Common.Domains.hhx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.Api.Application.wbxApplication.Commands.Role;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.RBAC.Api.Application.wbxApplication.Commands.User
{
    /// <summary>
    /// 个人信息反填handler
    /// </summary>
    public class SearchUserHandler : IRequestHandler<SearchUserCommand, Result<Users>>
    {
        private readonly IMapper mapper;
        /// <summary>
        /// 用户信息
        /// </summary>
        private readonly IBaseRepository<Users> usersrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchUserHandler> _logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper">mapper</param>
        /// <param name="usersrepository">usersrepository</param>
        /// <param name="logger">logger</param>
        public SearchUserHandler(IMapper mapper, IBaseRepository<Users> usersrepository, ILogger<SearchUserHandler> logger)
        {
            this.mapper = mapper;
            this.usersrepository = usersrepository;
            _logger = logger;
        }
        /// <summary>
        /// 个人信息反填
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result<Users>> Handle(SearchUserCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<Users>() { Code = (int)CommonErrorCode.Search };
            try
            {
                var user = await (await usersrepository.GetAll()).Where(x => x.UserId == request.UserId).FirstOrDefaultAsync();
                result.Data = user;
                result.Msg = "个人信息反填成功";
            }
            catch (Exception ex)
            {
                _logger.LogError("个人信息反填失败" + ex.Message);
                throw;
            }
            return result;
        }
    }
}
